package com.atguigu.gmall.common.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @Author: 李旭
 * @Time: 10:40
 * @Description:
 *
 *   远程调用拦截器
 *   远程调用之前拦截 处理相关业务  再远程调用
 *
 */
public class FeignInterceptor implements RequestInterceptor {
    //拦截器   执行方法
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //  任意位置获取当前微服务的请求对象
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();
        if(null != servletRequestAttributes){
            HttpServletRequest request = servletRequestAttributes.getRequest();
            if(null != request){
                //将当前请求对象头中的用户ID 传递给马上要发出的远程调用的请求对象
                Enumeration<String> headerNames = request.getHeaderNames();
                if(null != headerNames){//宽广
                    while (headerNames.hasMoreElements()){
                        String name = headerNames.nextElement();//name: content-length
                        if(name.equals("content-length")){
                            continue;
                        }
                        String value = request.getHeader(name);// value: too manay bytes writtern
                        System.out.println("name:" + name + "===value:" + value);
                        requestTemplate.header(name,value);
                    }
                }
           /* //狭隘  只传递用户ID
              String userId = request.getHeader("userId");
                if(!StringUtils.isEmpty(userId)){
                    //设置远程调用的请求对象头中
                    requestTemplate.header("userId",userId);
                }
            String userTempId = request.getHeader("userTempId");
                if(!StringUtils.isEmpty(userTempId)){
                    //设置远程调用的请求对象头中
                    requestTemplate.header("userTempId",userTempId);
                }
                */

            }
        }




    }
}
